package com.wlyuan.open.scanner.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlyuan.open.scanner.dao.entity.LinkManDO;
import com.wlyuan.open.scanner.dao.mapper.LinkManMapper;
import com.wlyuan.open.scanner.repository.LinkManRepository;
import com.wlyuan.open.scanner.utils.BatchSelectUtils;
import com.wlyuan.open.scanner.utils.StreamUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LinkManRepositoryImpl implements LinkManRepository {
    private final LinkManMapper linkManMapper;

    @Override
    public Map<Long, LinkManDO> getLinkManByAddrIds(List<Long> addrIds) {
        if (CollectionUtils.isEmpty(addrIds)) {
            return Collections.emptyMap();
        }
        addrIds = addrIds.stream().filter(x -> x != null).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(addrIds)) {
            return Collections.emptyMap();
        }
        //分批查询
        var list = BatchSelectUtils.batch(addrIds, this::select);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        //根据地址id分组 后取linkManId最大的
        return StreamUtils.maxByGroup(list, LinkManDO::getLinkmanAddrid, Comparator.comparing(LinkManDO::getLinkmanId));
    }

    @Override
    public LinkManDO getLinkManByAddrId(Long addrId) {
        return Optional.ofNullable(addrId).map(addressId -> {
            QueryWrapper<LinkManDO> query = new QueryWrapper<>();
            query.lambda().isNotNull(LinkManDO::getLinkmanName).isNotNull(LinkManDO::getLinkmanPhone)
                    .eq(LinkManDO::getLinkmanAddrid, addressId);
            return linkManMapper.selectOne(query);
        }).orElse(null);
    }

    private List<LinkManDO> select(List<Long> addrIds) {
        addrIds = addrIds.stream().filter(x -> x != null).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(addrIds)) {
            return Collections.emptyList();
        }
        QueryWrapper<LinkManDO> query = new QueryWrapper<>();
        query.lambda().isNotNull(LinkManDO::getLinkmanName).isNotNull(LinkManDO::getLinkmanPhone)
                .in(LinkManDO::getLinkmanAddrid, addrIds);
        return linkManMapper.selectList(query);
    }
}
